package services;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import com.aton.db.SessionFactory;

import models.BackCount;
import models.mappers.BackCountMapper;
import models.mappers.BackInfoMapper;
import models.mappers.DealerMapper;
import models.mappers.ShopMapper;
import vos.BackCountSearchVo;
import vos.BackCountSubSearchVo;
import vos.BackCountVo;
import vos.BackInfoVo;
import vos.UpdateBackCountVo;

public class BackCountService {
	private static final SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat monthFormater = new SimpleDateFormat("yyyy-MM");
	private static final SimpleDateFormat dateTimeFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	/**
	 * 统计当月经销商返款金额
	 *
	 * @Title: countMonth 
	 * @param operatorid 统计人
	 * @return
	 * @return: boolean
	 */
	public static boolean countMonth(String operatorid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			Date date=new Date();
			ShopMapper mapper = ss.getMapper(ShopMapper.class);
			//获取门店列表
			List<String> shops=mapper.listShopid();
			//获取当前日期的上个月份和下个月份
			Map<String,String> map=getFBMonth(date);
			BackCountMapper backmapper = ss.getMapper(BackCountMapper.class);
			//获取所有门店本月要统计的开始结束时间
			List<Map<String,String>> datemaps=getThisMonthDate(ss,shops,map,date);
			Map<String,Object> countmap=new HashMap<String,Object>();
			countmap.put("lists", datemaps);
			countmap.put("countname", operatorid);
			countmap.put("cmonth", monthFormater.format(date));
			backmapper.countMonth(countmap);
			ss.commit();
		}catch(Exception e){
			ss.rollback();
			e.printStackTrace();
			return false;
		}finally {
            ss.close();
        }
		return true;
	}
	/**
	 * 获取本月的开始结束时间
	 *
	 * @Title: getThisMonthDate 
	 * @param ss 数据库session
	 * @param shops 门店列表
	 * @param map 上、下月份
	 * @param date 统计月份时间
	 * @param ishand 是否为手动统计
	 * @return
	 * @return: Map<String,String>
	 */
	private static List<Map<String, String>> getThisMonthDate(SqlSession ss, List<String> shops, Map<String, String> map, Date date) {
		// TODO Auto-generated method stub
		try{
			BackCountMapper backmapper = ss.getMapper(BackCountMapper.class);
			List<Map<String,String>> lists=new ArrayList<Map<String,String>>();
			for(String shopid : shops){
				Map<String,String> newMap=new HashMap<String,String>();
				//获取上个月的开始结束时间
				Map<String,Date> fmap=backmapper.getStartEndDate(shopid,map.get("fmonth"));
				//获取下个月的开始结束时间
				Map<String,Date> bmap=backmapper.getStartEndDate(shopid,map.get("bmonth"));
				//获取上个月的最后一天
				String startdate="";
				String fmonthEnd=getMonthMaxDay(monthFormater.parse(map.get("fmonth")));
				//如果上月的结束时间小于最后一天，则本月开始时间为上月结束时间，否则为本月的最后一天
				if(fmap!=null&&StringUtils.isNotEmpty(fmonthEnd)&&dateTimeFormater.parse(fmonthEnd).getTime()>fmap.get("enddate").getTime()){
					startdate=dateTimeFormater.format(fmap.get("enddate"));
				}
				else{
						startdate=fmonthEnd;
				}
				String enddate="";
				//如果下月的开始时间小于本月的最后一天，则本月的结束时间为下月的开始时间，否则为本月的最后一天
				String thisMonthEnd=getMonthMaxDay(date);
				if(bmap!=null&&StringUtils.isNotEmpty(thisMonthEnd)&&dateTimeFormater.parse(thisMonthEnd).getTime()>bmap.get("startdate").getTime()){
					enddate=dateTimeFormater.format(bmap.get("startdate"));
				}
				else{
					Date today=new Date();
					//如果本月的最后一天大于当前日期，则以当前日期为结束时间
					if(dateTimeFormater.parse(thisMonthEnd).getTime()>today.getTime()){
						enddate=dateTimeFormater.format(today);
					}
					else{
						enddate=thisMonthEnd;
					}
				}
				newMap.put("startdate", startdate);
				newMap.put("enddate", enddate);
				newMap.put("shopid",shopid);
				lists.add(newMap);
			}
			return lists;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 返回本月的最后一天
	 *
	 * @Title: getMonthMaxDay 
	 * @return
	 * @return: String
	 */
	public static String getMonthMaxDay(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
        // 设置日期为本月最大日期
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

        // 打印
       return dateFormater.format(calendar.getTime())+" 23:59";
	}
	/**
	 * 获取上个月和下个月
	 *
	 * @Title: getFMonth 
	 * @param date
	 * @return
	 * @return: String
	 */
	public static Map<String,String> getFBMonth(Date date){
		Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -1);
        String fmonth=monthFormater.format(cal.getTime());
        Map<String,String> map=new HashMap<String,String>();
        cal.add(Calendar.MONTH, 2);
        map.put("fmonth", fmonth);
        String bmonth=monthFormater.format(cal.getTime());
        map.put("bmonth", bmonth);
        return map;
	}
	/**
	 * 获取上个月统计时间
	 * @param date 
	 *
	 * @Title: getLastTime 
	 * @return
	 * @return: String
	 */
	public static Date getLastTime(Date date){
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			Calendar cal = Calendar.getInstance();
	        cal.setTime(date);
	        cal.add(Calendar.MONTH, -1);
	        String cmonth=monthFormater.format(cal.getTime());
	       // String enddate=getMonthMaxDay(cal.getTime());
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			//根据上月的开始时间，结束时间查询是否有统计时间
			return mapper.getLastTime(cmonth);
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取未保存记录
	 *
	 * @Title: getCount 
	 * @param page 页
	 * @param rows 页数量
	 * @param sort 排序字段
	 * @param order 排序方式
	 * @return
	 * @return: List<BackCountVo>
	 */
	public static List<BackCountVo> getCount(BackCountSearchVo vo) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.getCount(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取列表总数
	 *
	 * @Title: count 
	 * @param vo
	 * @return
	 * @return: long
	 */
	public static long count(BackCountSearchVo vo) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.count(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 统计该月份所有记录总数
	 *
	 * @Title: countByMonth 
	 * @return
	 * @return: Long
	 */
	public static Long countByMonth(String month) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.countByMonth(month);
        } finally {
            ss.close();
        }
	}
	/**
	 * 统计未保存的记录数
	 *
	 * @Title: countBySave 
	 * @return
	 * @return: Long
	 */
	public static Long countBySave() {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.countBySave();
        } finally {
            ss.close();
        }
	}
	/**
	 * 重新统计
	 *
	 * @Title: reCount 
	 * @param operatorid 操作人
	 * @return
	 * @return: boolean
	 */
	public static boolean reCount(String operatorid) {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			List<BackCount> backs=getNotSave();
			Date date=new Date();
			List<UpdateBackCountVo> counts=new ArrayList<UpdateBackCountVo>();
			Map<String,Object> map=new HashMap<String,Object>();
			for(BackCount count :backs){
				UpdateBackCountVo vo=new UpdateBackCountVo(count.shopid,dateTimeFormater.format(count.startdate),
						dateTimeFormater.format(count.enddate),operatorid,date,count.cmonth);
				counts.add(vo);
			}
			map.put("lists", counts);
			mapper.reCount(map);
            ss.commit();
        }catch(Exception e){ 
        	ss.rollback();
        	e.printStackTrace();
        	return false;
        }
		finally {
            ss.close();
        }
		return true;
	}
	/**
	 * 获取未保存的记录
	 *
	 * @Title: getNotSave 
	 * @return
	 * @return: boolean
	 */
	public static List<BackCount> getNotSave(){
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.getNotSave();
        } finally {
            ss.close();
        }
	}
	/**
	 * 删除未保存记录
	 *
	 * @Title: delCount 
	 * @return
	 * @return: boolean
	 */
	public static boolean delCount() {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            mapper.delCount();
            ss.commit();
        }catch(Exception e){
        	ss.rollback();
        	e.printStackTrace();
        	return false;
        }
		finally {
            ss.close();
        }
		return true;
	}
	/**
	 * 保存未保存数据
	 *
	 * @Title: saveCount 
	 * @return
	 * @return: boolean
	 */
	public static boolean saveCount() {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            //mapper.saveCount();
            mapper.updateSave();
            ss.commit();
        }catch(Exception e){
        	ss.rollback();
        	e.printStackTrace();
        	return false;
        }
		finally {
            ss.close();
        }
		return true;
	}
	/**
	 * 手动统计
	 *
	 * @Title: handCount 
	 * @param operatorid 统计人
	 * @param cmonth 统计月份
	 * @return
	 * @return: boolean
	 */
	public static boolean handCount(String operatorid, String cmonth) {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try {
			Date date=monthFormater.parse(cmonth);
			ShopMapper mapper = ss.getMapper(ShopMapper.class);
			//获取门店列表
			List<String> shops=mapper.listShopid();
			//获取当前日期的上个月份和下个月份
			Map<String,String> map=getFBMonth(date);
			BackCountMapper backmapper = ss.getMapper(BackCountMapper.class);
			//获取所有门店本月要统计的开始结束时间
			List<Map<String,String>> datemaps=getThisMonthDate(ss,shops,map,date);
			Map<String,Object> countmap=new HashMap<String,Object>();
			countmap.put("lists", datemaps);
			countmap.put("countname", operatorid);
			countmap.put("cmonth", monthFormater.format(date));
			backmapper.countMonth(countmap);
			ss.commit();
		}catch(Exception e){
			ss.rollback();
			e.printStackTrace();
			return false;
		}finally {
            ss.close();
        }
		return true;
	}
	/**
	 * 根据经销商id和时间查询数据
	 *
	 * @Title: getByDealerMonth 
	 * @param shopid
	 * @param cmonth
	 * @return
	 * @return: BackCount
	 */
	public static BackCount getByDealerMonth(String shopid, String cmonth) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			return mapper.getByShopMonth(shopid,cmonth);
        } finally {
            ss.close();
        }
	}
	/**
	 * 统计子表信息
	 * 子表为每日数据统计
	 * @Title: countSub 
	 * @param vo
	 * @return
	 * @return: long
	 */
	public static long countSub(BackCountSubSearchVo vo) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			return mapper.countSub(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取子表列表
	 *
	 * @Title: getCountSub 
	 * @param vo
	 * @return
	 * @return: List<BackCountVo>
	 */
	public static List<BackCountVo> getCountSub(BackCountSubSearchVo vo) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			return mapper.getCountSub(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取引用统计返款的条数
	 *
	 * @Title: countByBack 
	 * @param vo
	 * @return
	 * @return: long
	 */
	public static long countByBack(BackCountSearchVo vo) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.countByBack(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 获取引用统计返款记录
	 *
	 * @Title: getCountByBack 
	 * @param vo
	 * @return
	 * @return: List<BackCountVo>
	 */
	public static List<BackCountVo> getCountByBack(BackCountSearchVo vo) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.getCountByBack(vo);
        } finally {
            ss.close();
        }
	}
	/**
	 * 根据ids获取记录
	 *
	 * @Title: getByIds 
	 * @param listid
	 * @return
	 * @return: List<BackInfoVo>
	 */
	public static List<BackCountVo> getByIds(List<String> listid) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("listId", listid);
            return mapper.getByIds(map);
        } finally {
            ss.close();
        }
	}
	/**
	 * 批量驳回
	 *
	 * @Title: betchReject 
	 * @param listid
	 * @param operatorid
	 * @param rejreason
	 * @return
	 * @return: boolean
	 */
	public static boolean betchReject(List<String> listid, String operatorid, String rejreason) {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			Map<String,Object> map=new HashMap<>();
			map.put("listId", listid);
			Date date=new Date();
			map.put("modifytime", date);
			map.put("modifyname", operatorid);
			map.put("rejreason", rejreason);
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			mapper.betchReject(map);
			ss.commit();
		}catch(Exception e){
			ss.rollback();
			e.printStackTrace();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 根据id获取记录信息
	 *
	 * @Title: getById 
	 * @param id
	 * @return
	 * @return: BackCountVo
	 */
	public static BackCountVo getById(Long id) {
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
            return mapper.getById(id);
        } finally {
            ss.close();
        }
	}
	/**
	 * 驳回统计
	 *
	 * @Title: reject 
	 * @param id
	 * @param operatorid
	 * @param rejreason
	 * @return
	 * @return: boolean
	 */
	public static boolean reject(Long id, String operatorid, String rejreason) {
		SqlSession ss = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			Map<String,Object> map=new HashMap<>();
			BackCountMapper mapper = ss.getMapper(BackCountMapper.class);
			map.put("id", id);
			Date date=new Date();
			map.put("modifytime", date);
			map.put("modifyname", operatorid);
			map.put("rejreason", rejreason);
			mapper.reject(map);
			ss.commit();
		}catch(Exception e){
			ss.rollback();
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
